package com.lqb.webScaffold.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.lqb.webScaffold.entity.Users;
import com.lqb.webScaffold.service.impl.UsersServiceImpl;
import com.lqb.webScaffold.utils.HutoolRSA;
import com.lqb.webScaffold.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author lqb
 * @since 2023-03-19
 */
@RestController
@RequestMapping("/users")
public class UsersController {
    @Resource
    private UsersServiceImpl usersService;
    @Resource
    private HutoolRSA hutoolRSA;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private RedissonClient redissonClient;
    @PostMapping("/login")
    @ResponseBody
    public R getUser(@RequestBody Users parame, HttpServletRequest request) throws IOException {
        String key = "login_attempts:" + parame.getAccount();
        RBucket<Integer> rBucket = redissonClient.getBucket(key);//获取用户的储存桶
        Integer num = rBucket.get();
        num = (num == null)?0:num;
        if( num >= 3 ){
            return R.failed("密码错误次数过多，请稍后尝试！").setCode(403);
        }
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>(new Users());
        queryWrapper.eq("account",parame.getAccount());
        Users user = usersService.getOne(queryWrapper);
        if( user!=null && hutoolRSA.decrypt(user.getPassword()).equals(parame.getPassword()) ){
            String token = jwtUtils.generateToken(user.getId());
            HashMap<String,Object> map = new HashMap<>();
            map.put("token",token);
            map.put("user",user);
            rBucket.delete();
            return R.ok(map).setMsg("登录成功！");
        }
        num = num + 1;
        rBucket.set(num, 15,TimeUnit.MINUTES);//将密码错误次数+1，保存15分钟
        return R.failed("账号或密码不正确！").setCode(403);
    }

    @PostMapping("/session")
    @ResponseBody
    public R getUserBySession(HttpServletRequest request) throws IOException {
        String token = request.getHeader("Authorization");
        if( token!=null ) token = token.replace("Bearer ","");
        String userId = jwtUtils.parseToken(token);
        if( userId != null ){
            System.out.println(userId);
            Users user = usersService.getById(userId);
            return R.ok(user).setMsg("欢迎你，"+user.getAccount()+"!");
        }
        return R.failed("会话已过期，请重新登录！").setCode(401);
    }

    @PostMapping("/register")
    @ResponseBody
    public R addUser(@RequestBody Users parame, HttpServletRequest request) throws IOException {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>(new Users());
        queryWrapper.eq("account", parame.getAccount());
        Users user = usersService.getOne(queryWrapper);
        if (user == null) {
            Users user1 = new Users();
            user1.setAccount(parame.getAccount());
            user1.setPassword(hutoolRSA.encrypt(parame.getPassword()));
            boolean res = usersService.save(user1);
            if (res) {
                queryWrapper = new QueryWrapper<>(new Users());
                queryWrapper.eq("account", user1.getAccount());
                user1 = usersService.getOne(queryWrapper);
                return R.ok(user1).setMsg("注册成功！");
            }
        }
        return R.failed("用户名已存在！").setCode(403);
    }

    @PostMapping("/update")
    @ResponseBody
    public R updateUser(@RequestBody Users parame, HttpServletRequest request) throws IOException {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>(new Users());
        queryWrapper.eq("account", parame.getAccount());
        Users user = usersService.getOne(queryWrapper);
        if (user != null) {
            Boolean res = usersService.updateById(parame);
            if( res ){
                user = usersService.getOne(queryWrapper);
                return R.ok(user).setMsg("保存成功！");
            }else{
                return R.failed("保存失败，请重试！").setCode(403);
            }
        }
        return R.failed("用户不存在！").setCode(403);
    }
}
